package com.ljx.offer;

import java.util.LinkedList;

/**
 * @author 李捷禧
 * Date: 2023/3/16
 * ClassName: C_18
 */

public class C_18 {


    public ListNode deleteNode3(ListNode head, int val) {
        ListNode pre = head, cur = head.next;
        if(head.val == val) return head.next;
        while(cur != null && cur.val != val){
            pre = cur;
            cur = cur.next;
        }
        //链表下一个数等于val时
        if(cur != null) pre.next = cur.next;
        return head;
    }

    /**
     * 暴力解法
     * @param head
     * @param val
     * @return
     */
    public ListNode deleteNode(ListNode head, int val) {
        LinkedList<Integer> list = new LinkedList<>();
        while(head!=null){
            if(head.val!=val){
                list.addLast(head.val);
            }
            head = head.next;
        }
        ListNode listNode = new ListNode(0),res = listNode;
        while(!list.isEmpty()){
            res.next = new ListNode(list.removeFirst());
            res = res.next;
        }
        return listNode.next;
    }

    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }
}
